﻿using MaterialTypeRecognition.Shell.AuthenticationServices.Extensions;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace MaterialTypeRecognition.Shell
{
    public class WebStartup
    {
        private readonly IConfiguration _configuration;

        public WebStartup(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        public void ConfigureServices(IServiceCollection services)
        {
            // 添加所需的服务依赖项
            services.AddControllers();
            services.AddJwtBearerService(_configuration);
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            // 配置 CORS
            app.UseCors(builder =>
            {
                builder.AllowAnyOrigin() // 允许任何来源的请求
                    .AllowAnyMethod() // 允许任何HTTP方法
                    .AllowAnyHeader(); // 允许任何HTTP头部
            });

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                // 添加生产环境中的错误处理中间件
                app.UseExceptionHandler("/Error");
                app.UseHsts();
            }

            app.UseRouting();

            // 方法调用顺序不得更改。
            app.UseAuthentication(); // 使用认证。
            app.UseAuthorization();  // 使用授权。

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}
